package com.javalong.androidmorning.wechat.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.javalong.androidmorning.common.util.CodeUtils;
import com.javalong.androidmorning.common.util.XMLUtils;
import com.javalong.androidmorning.dao.ResponseMessageDao;
import com.javalong.androidmorning.pojo.Article;
import com.javalong.androidmorning.pojo.Keyword;
import com.javalong.androidmorning.pojo.ResponseMessage;

/**
 * 主要对微信的请求及返回数据作处理
 * 
 * @author Administrator
 *
 */
@Service
public class ResponseMessageService {

	private final static String ToUserName = "ToUserName";
	private final static String FromUserName = "FromUserName";
	private final static String CreateTime = "CreateTime";
	private final static String MsgType = "MsgType";
	private final static String Content = "Content";
	private final static String MsgId = "MsgId";
	private final static String ArticleCount = "ArticleCount";
	private final static String Title = "Title";
	private final static String Description = "Description";
	private final static String PicUrl = "PicUrl";
	private final static String Url = "Url";
	private final static String Item = "item";

	private final static String ArticlePrefix = "http://120.25.175.172/zdk/dwz/article_detail/view?id=";

	private final static String DEFAULT_RESPONSE = "欢迎关注安卓早读课，本公众号正在努力构建中，有好的建议或者合作意向请直接发送消息给公众号，我会定时查看！";

	@Autowired
	private KeywordService keywordService;
	@Autowired
	private ResponseMessageDao responseMessageDao;
	@Autowired
	private ArticleService articleService;

	/**
	 * 根据不同的请求数据返回不同的请求内容
	 * 
	 * @param map
	 */
	public String dealMessageMap(Map<String, String> map) {
		String msgType = map.get(MsgType);
		if ("text".equals(msgType)) {
			String keyword = map.get(Content);
			return dealTextKeyword(keyword, map);
		}
		return responseTextMessage(DEFAULT_RESPONSE, map);
	}

	/**
	 * 处理关键字
	 * 
	 * @param keyword
	 */
	private String dealTextKeyword(String keyword, Map<String, String> map) {
		if (StringUtils.isEmpty(keyword))
			return null;
		Keyword _keyword = keywordService.matchKeyword(keyword);
		if (_keyword == null)
			return null;
		int resId = _keyword.getResId();
		if (resId > 0) {
			ResponseMessage responseMessage = responseMessageDao.findById(resId);
			if (responseMessage == null)
				return null;

			int msgType = responseMessage.getMsgType();

			switch (msgType) {
			case 1:
				return responseTextMessage(responseMessage.getContent(), map);
			case 6:
				return responseArticleMessage(responseMessage, map);
			}
		}
		return null;
	}

	/**
	 * 创建文本回复
	 */
	private String responseTextMessage(String responseText, Map<String, String> map) {
		if (StringUtils.isEmpty(responseText))
			return null;
		Map<String, String> responseMap = new HashMap<String, String>();
		responseMap.put(MsgType, "text");
		responseMap.put(ToUserName, map.get(FromUserName));
		responseMap.put(FromUserName, map.get(ToUserName));
		responseMap.put(CreateTime, new Date().getTime() + "");
		responseMap.put(Content, responseText);
		return CodeUtils.encodeResponseXml(XMLUtils.parseMap2Xml(responseMap));
	}

	/**
	 * 创建图文回复
	 */
	private String responseArticleMessage(ResponseMessage responseMessage, Map<String, String> map) {
		List<Article> articleList = articleService.findArticleByResid(responseMessage.getId());
		if (articleList == null || articleList.size() == 0) {
			return null;
		}

		Map<String, String> responseMap = new HashMap<String, String>();
		responseMap.put(MsgType, "news");
		responseMap.put(ToUserName, map.get(FromUserName));
		responseMap.put(FromUserName, map.get(ToUserName));
		responseMap.put(CreateTime, new Date().getTime() + "");
		responseMap.put(CreateTime, new Date().getTime() + "");
		responseMap.put(ArticleCount, articleList.size() + "");

		Element root = DocumentHelper.createElement("xml");
		Document document = DocumentHelper.createDocument(root);
		for (Entry<String, String> entry : responseMap.entrySet()) {
			String qName = entry.getKey();
			String text = entry.getValue();
			Element element = DocumentHelper.createElement(qName);
			element.setText(text);
			root.add(element);
		}
		Element articles = DocumentHelper.createElement("Articles");
		root.add(articles);
		for (Article article : articleList) {
			Element item = DocumentHelper.createElement(Item);
			articles.add(item);

			Element itemTitle = DocumentHelper.createElement(Title);
			Element itemDescription = DocumentHelper.createElement(Description);
			Element itemPicUrl = DocumentHelper.createElement(PicUrl);
			Element itemUrl = DocumentHelper.createElement(Url);

			itemTitle.setText(article.getTitle());
			itemDescription.setText(article.getDescription());
			itemPicUrl.setText(article.getPicUrl());
			String url = article.getUrl();
			if (url.startsWith("article:")) {
				String articleId = url.substring("article:".length());
				itemUrl.setText(ArticlePrefix + "" + articleId);
			} else {
				itemUrl.setText(article.getUrl());
			}
			item.add(itemTitle);
			item.add(itemDescription);
			item.add(itemPicUrl);
			item.add(itemUrl);
		}

		return CodeUtils.encodeResponseXml(document.asXML());
	}

	public List<ResponseMessage> getList(int page, int pageSize) {
		return responseMessageDao.findAll(page * pageSize, pageSize);
	}

	public void delete(int id) {
		responseMessageDao.delete(id);
	}

	public void save(ResponseMessage responseMessage) {
		Date now = new Date();
		responseMessage.setCreateAt(now);
		responseMessage.setUpdateAt(now);
		responseMessageDao.save(responseMessage);
	}

	public int getCount() {
		return responseMessageDao.getCount();
	}

	public void update(ResponseMessage responseMessage) {
		Date now = new Date();
		responseMessage.setUpdateAt(now);
		responseMessageDao.update(responseMessage);
	}

	public ResponseMessage findById(int id) {
		return responseMessageDao.findById(id);
	}
}
